﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Sausage.Common
{
    public class HtmlHandleErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext exceptionContext)
        {
            if (exceptionContext.Exception != null)
            {
                var content = new ContentResult();
                string errorHtml;

                if (exceptionContext.Exception is UnauthenticatedException)
                {
                    errorHtml = "您还没有登录，请登录!";
                    exceptionContext.HttpContext.Response.StatusCode = (int)SausageHttpErrorCode.Unauthenticated;
                }
                else if (exceptionContext.Exception is UnauthorizedException)
                {
                    errorHtml = "您没有获得授权，浏览此信息!";
                    exceptionContext.HttpContext.Response.StatusCode = (int)SausageHttpErrorCode.Unauthorized;
                }
                else if (exceptionContext.Exception is SausageException)
                {
                    errorHtml = exceptionContext.Exception.Message;
                    exceptionContext.HttpContext.Response.StatusCode = (int)SausageHttpErrorCode.CommonError;
                }
                else
                {
                    errorHtml = "对不起，系统出错了，请稍后再试！";
                    exceptionContext.HttpContext.Response.StatusCode = (int)SausageHttpErrorCode.CommonError;
                }

#if DEBUG
                errorHtml = exceptionContext.Exception.ToString();
#endif
                content.Content = errorHtml;

                exceptionContext.HttpContext.Response.TrySkipIisCustomErrors = true;

                exceptionContext.Result = content;

                exceptionContext.ExceptionHandled = true;

            }
        }
    }
}
